<template>
    <panelHead :route="route"/>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>基本资料</span>
            </div>
        </template>
        <!-- 将用户资料和密码修改部分并列展示 -->
        <el-row gutter="20">
            <!-- 左侧：用户信息修改 -->
            <el-col :span="12">
                <el-form :model="userInfo" :rules="rules" label-width="100px" size="large" class="user-info-form">
                    <!-- 用户头像上传 -->
                    <el-form-item label="用户头像" prop="userPic" class="avatar-form-item">
                        <div class="avatar-upload-section">
                            <el-upload
                                ref="uploadRef"
                                class="avatar-uploader"
                                action="/api/upload"
                                :auto-upload="true"
                                name="file"
                                :show-file-list="false"
                                :on-success="uploadSuccess"
                                :headers="{ 'Authorization': token }"
                            >
                                <img :src="userInfo.userPic || avatar" class="avatar" />
                                <el-button type="primary" :icon="Plus" >
                                    上传头像</el-button>
                            </el-upload>
                            <el-button type="primary" @click="updateUserAvatar" :icon="Upload">保存头像修改</el-button>
                        </div>
                    </el-form-item>

                    <el-form-item label="登录名称">
                        <el-input v-model="userInfo.username" disabled></el-input>
                    </el-form-item>

                    <el-form-item label="用户昵称" prop="nickname">
                        <el-input v-model="userInfo.nickname"></el-input>
                    </el-form-item>

                    <el-form-item label="用户邮箱" prop="email">
                        <el-input v-model="userInfo.email"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="updateUserInfo" :icon="Upload">保存资料修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <!-- 右侧：用户密码修改 -->
            <el-col :span="12">
                <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" size="large" class="password-form">
                    <div class="form-header">修改密码</div>
                    
                    <el-form-item label="原密码" prop="oldPassword">
                        <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
                    </el-form-item>

                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
                    </el-form-item>

                    <el-form-item label="确认新密码" prop="confirmPassword">
                        <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="updateUserPassword" :icon="Upload">保存密码修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userInfoUpdateService, userAvatarUpdateService, userPasswordUpdateService } from '@/api/user.js'
import { useRoute } from 'vue-router'
import { Upload, Plus } from '@element-plus/icons-vue'
import useUserInfoStore from '@/store/userInfo.js'
import avatar from '@/assets/default.png'
const userInfoStore = useUserInfoStore();

const route = useRoute()
const userInfo = ref({...userInfoStore.info})
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})
const token =localStorage.getItem('min_token')
const rules = {
    nickname: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { pattern: /^\S{2,10}$/, message: '昵称必须是2-10位的非空字符串', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入用户邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ]
}
const passwordRules = {
    oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: (rule, value, callback) => {
            if (value !== passwordForm.value.newPassword) {
                callback(new Error('两次输入的密码不一致'))
            } else {
                callback()
            }
        }, trigger: 'blur' }
    ]
}

// 修改昵称和邮箱
const updateUserInfo = async () => {
    try {
        const result = await userInfoUpdateService(userInfo.value)
        if (result.data.code === 0) {
            ElMessage({
                message: "资料修改成功",
                type: 'success'
            })
            userInfoStore.setInfo(userInfo.value)
            //localStorage.setItem('min_userInfo', JSON.stringify(userInfo.value))
        } else {
            ElMessage({
                message: result.data.message,
                type: 'error'
            })
        }
    } catch (error) {
        console.error('用户信息修改失败', error)
    }
}

// 修改头像
const updateUserAvatar = async () => {
    try {
        const result = await userAvatarUpdateService(userInfo.value.userPic)
        console.log('result',result)
        console.log('group_avatar', userInfo.value.userPic)
        userInfoStore.info.userPic = userInfo.value.userPic
        if (result.data.code === 0) {
            
            ElMessage({
                message: "头像修改成功",
                type: 'success'
            })
        } else {
            ElMessage({
                message: '头像修改失败：' + result.data.message,
                type: 'error'
            })
        }
    } catch (error) {
        console.error('头像修改失败', error)
    }
}

//图片上传成功的回调函数
const uploadSuccess = (result)=>{
    userInfo.value.userPic = result.data;
}

// 修改密码
const updateUserPassword = async () => {
    const token = localStorage.getItem('min_token');
    
    try {
        await passwordFormRef.value.validate();  // 触发表单校验
        const data = {
            old_pwd: passwordForm.value.oldPassword,
            new_pwd: passwordForm.value.newPassword,
            re_pwd: passwordForm.value.confirmPassword
        }
        
        const response = await userPasswordUpdateService(data, token);
        
        if (response.data.code === 0) {
            ElMessage({
                message: "密码修改成功",
                type: 'success'
            })
            passwordForm.value.oldPassword = '';
            passwordForm.value.newPassword = '';
            passwordForm.value.confirmPassword = '';
            userInfoStore.info.password = userInfo.value.password
            // 清除本地token, 强制用户重新登录
            localStorage.removeItem('min_token');
            ElMessage({
                type: 'warning',
                message: '密码修改成功，请重新登录'
            })
            setTimeout(() => {
                window.location.href = '/user/login';
            }, 1500);
        } else {
            ElMessage({
                message: response.data.message,
                type: 'error'
            })
        }
    } catch (error) {
        console.error('密码修改失败', error);
    }
}

</script>

<style lang="less" scoped>
.page-container {
    padding: 20px;
    background: #f5f7fa;
    border-radius: 12px;
    margin-top: 15px;
}

.header {
    font-size: 1.5rem;
    margin-bottom: 20px;
}

.user-info-form, .password-form {
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    margin-bottom: 30px;
}
.avatar-form-item {
  align-items: center;
  display: flex; 
  :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
  }
}
.avatar-upload-section {
    display: flex;
    align-items: center;
    gap: 20px;
}

.avatar-uploader {
    margin-right: 10px;
    margin-top: 12px;
}

.avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 15px;
}

.form-header {
    font-weight: bold;
    margin-bottom: 15px;
    font-size: 1.2rem;
    padding: 29px;
    object-fit: cover;
}
</style>

